﻿namespace CatClient
{
    using CatClient.Context;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Specialized;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Web;

    public static class CatCoreUtils
    {
        public static string GetClientIp()
        {
            try
            {
                if (HttpContext.Current == null)
                {
                    return "127.0.0.1";
                }
                NameValueCollection serverVariables = HttpContext.Current.Request.ServerVariables;
                string str = serverVariables["REMOTE_ADDR"] ?? "";
                string str2 = serverVariables["HTTP_CLIENT_IP"] ?? "";
                if (string.IsNullOrEmpty(str2))
                {
                    str2 = str;
                }
                if (string.IsNullOrEmpty(str2))
                {
                    str2 = "127.0.0.1";
                }
                return str2;
            }
            catch
            {
                return "127.0.0.1";
            }
        }

        public static string HttpContextParams()
        {
            if (HttpContext.Current == null)
            {
                return string.Empty;
            }
            StringBuilder builder = new StringBuilder();
            NameValueCollection queryString = HttpContext.Current.Request.QueryString;
            foreach (string str in queryString.Keys)
            {
                if (str != null)
                {
                    builder.Append($"{str}={queryString[str]}&");
                }
            }
            return builder.ToString();
        }

        public static CatResponseContext ToCatResponseContext(this string contextString)
        {
            if (!string.IsNullOrEmpty(contextString))
            {
                try
                {
                    return JsonConvert.DeserializeObject<CatResponseContext>(contextString);
                }
                catch
                {
                    Cat.LogEvent("PigeonCall.AppFormatError", contextString, "0", null);
                }
            }
            return null;
        }
    }
}

